import libtcodpy as libtcod


class ViewPort:

    def __init__(self, width, height, map):

        self.width = width
        self.height = height

        self.mapWidth = map.width
        self.mapHeight = map.height

        # Which part of the map to display
        self.mapX = 0
        self.mapY = (map.height - height) / 2

        return

    def draw(self, console, map):

        for x in range(self.width):
            for y in range(self.height):

                relMapX = self.mapX + x
                relMapY = self.mapY + y

                tile = map.tiles[relMapX][relMapY]

                drawChar = " "
                drawColor = libtcod.white
                drawBackground = libtcod.BKGND_NONE

                if len(tile.stack) > 0:
                    top = tile.stack[-1]

                    drawChar = top.icon
                    drawColor = top.textColor
                    drawBackground = top.backgroundColor

                # Set the color
                # TODO: Why is the first argument 0
                libtcod.console_set_default_foreground(0, drawColor)

                # Draw the object to the console
                # TODO: Why is the first argument 0
                libtcod.console_put_char(0, x, y, drawChar, libtcod.BKGND_NONE)

                if drawBackground:
                    libtcod.console_set_char_background(0, x, y, drawBackground, libtcod.BKGND_SET)

        return

    def handleInput(self):
        # print "Handle Input"

        key = libtcod.console_check_for_keypress()

        if libtcod.console_is_key_pressed(libtcod.KEY_UP):
            if self.mapY > 0:
                self.mapY -= 1
                # print "Move Up"

        if libtcod.console_is_key_pressed(libtcod.KEY_DOWN):
            if self.mapY < self.mapHeight - self.height:
                self.mapY += 1
                # print "Move Down"

        if libtcod.console_is_key_pressed(libtcod.KEY_LEFT):
            if self.mapX > 0:
                self.mapX -= 1
                # print "Move Left"

        if libtcod.console_is_key_pressed(libtcod.KEY_RIGHT):
            if self.mapX < self.mapWidth - self.width:
                self.mapX += 1
                # print "Move Right"

